(function(){
  'use strict';

  angular
    .module('client')
    .config(routerConfig);

  routerConfig.$inject = ['$stateProvider', '$urlRouterProvider'];
  function routerConfig($stateProvider, $urlRouterProvider) {
    $urlRouterProvider
      .otherwise('/');

    $stateProvider
      .state('auth', {
        url: '/auth',
        template: '<div ui-view></div>',
        data: {
          goDash: true,
        },
      })
      .state('auth.login', {
        url: '/login',
        templateUrl: 'app/auth/auth.login.html',
        controller: 'LoginController',
        controllerAs: 'vm',
      })
      .state('device', {
        url: '/',
        templateUrl: 'app/device/device.html',
        controller: 'DeviceController',
        controllerAs: 'vm',
        data: {
          needAuthenticated: true,
        },
      })
      .state('control', {
        url: '/control/:deviceID',
        templateUrl: 'app/control/control.html',
        controller: 'ControlController',
        controllerAs: 'vm',
        data: {
          needAuthenticated: true,
        },
        resolve: {
          available: function($q, $http, $stateParams, $state, AVAILABLE_API) {
            var d = $q.defer();
            $http.get(AVAILABLE_API.isAvailable + $stateParams.deviceID + AVAILABLE_API.postfix)
              .then(function (response) {
                  if(response.data.data.isAvailable) {
                    d.resolve(response.data)
                  }
                  else {
                    $state.go('device');
                    d.reject(response.data);
                  }
              }, function (err) {
                $state.go('device');
                d.reject(err);
              });
            return d.promise;
          }
        },
      })
      .state('control.logs', {
        views: {
          info: {
            controller: 'LogcatController',
            controllerAs: 'logCtrl',
            templateUrl: 'app/control/logcat/logcat.html',
          }
        }
      })
  }
})();
